package net.qhzw.vip.qiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.qhzw.vip.qiyu.entity.*;
import net.qhzw.vip.qiyu.handler.ApiException;
import net.qhzw.vip.qiyu.mapper.DtsCarTransferMapper;
import net.qhzw.vip.qiyu.model.ContractData;
import net.qhzw.vip.qiyu.model.DtsCarTransferForm;
import net.qhzw.vip.qiyu.model.DtsCarTransferVo;
import net.qhzw.vip.qiyu.service.*;
import net.qhzw.vip.qiyu.util.RedisUtils;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
public class DtsCarTransferServiceImpl extends ServiceImpl<DtsCarTransferMapper, DtsCarTransfer> implements DtsCarTransferService {


    @Autowired
    private DtsCarTransferMapper dtsCarTransferMapper;

    @Autowired
    private DtsCarRentalService dtsCarRentalService;

    @Autowired
    private DtsCarTransferMaintService dtsCarTransferMaintService;

    @Autowired
    private RepairCodeService repairCodeService;

    @Autowired
    private GuaranteeCompanyService guaranteeCompanyService;

    @Autowired
    private RepairMaintService repairMaintService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private PayService payService;

    @Autowired
    private DtsCarTransferRefundService carTransferRefundService;

    /***
     * 查询换车申请列表
     * @param page
     * @return
     */
    @Override
    public Map<String, Object> findByPage(Page<DtsCarTransfer> page, String idCard, String mobile, String realName, Long shopId) {
        SysUser user = sysUserService.getById(SecurityUtils.getUserId());
        if (user == null || user.getCommunityId() == null) {
            return new HashMap<>();
        }
        Long communityId = null;
        if (user.getCommunityId() != 1L) {
            communityId = user.getCommunityId();
        }
        PageHelper.startPage((int) page.getCurrent(), (int) page.getSize());
        List<DtsCarTransferVo> dtsCarTransferVos = dtsCarTransferMapper.findByPage(idCard, mobile, realName, communityId, shopId);
        PageInfo<DtsCarTransferVo> pageInfo = new PageInfo<>(dtsCarTransferVos);
        List<DtsCarTransferVo> infoList = pageInfo.getList();
        if (!CollectionUtils.isEmpty(infoList)) {
            for (DtsCarTransferVo dtsCarTransferVo : infoList) {
                Long userId = dtsCarTransferVo.getUserId();
                String companyServiceName = guaranteeCompanyService.getNameByUserId(userId);
                dtsCarTransferVo.setGuaranteeCompanyName(companyServiceName);
                List<RepairMaint> repairMaints = getRepairMaintsById(dtsCarTransferVo.getId());
                dtsCarTransferVo.setRepairMaints(repairMaints);
                dtsCarTransferVo.setMaintSum(dtsCarTransferVo.getMaintFee().add(dtsCarTransferVo.getOthrFee()));
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("total", (int) pageInfo.getTotal());
        result.put("records", pageInfo.getList());
        return result;
    }


    /***
     * 根据换车申请id查询配件列表
     * @param id
     * @return
     */
    private List<RepairMaint> getRepairMaintsById(Long id) {
        return repairMaintService.listByTransferId(id);
    }


    /***
     * 换车申请
     * @param form
     * @return
     */
    @Override
    public boolean carChgApp(DtsCarTransferForm form, HttpServletRequest request) {
        checked(form);
        long carTransId = IdWorker.getId();
        DtsCarTransfer dtsCarTransferDB = addDtsCarTransfer(form);
        //插入中间表数据
        updMaint(carTransId, form);
        //修改车辆
        updateRepairCode(form);
        //修改租车表
        updateDtsCarRental(form, request);
        Long carRentalId = form.getCarRentalId();
        int count = count(new LambdaQueryWrapper<DtsCarTransfer>()
                .eq(DtsCarTransfer::getCarRentalId, carRentalId));
        if (count > 0) {
            Long id = dtsCarTransferMapper.getIdByCarRentalId(carRentalId);
            updMaint(carTransId, form);
            dtsCarTransferDB.setId(id);
            return updateById(dtsCarTransferDB);
        } else {
            dtsCarTransferDB.setId(carTransId);
            return save(dtsCarTransferDB);
        }
    }

    /**
     * 初始化表单数据
     *
     * @param form
     * @return
     */
    private DtsCarTransfer addDtsCarTransfer(DtsCarTransferForm form) {
        String feeStatus = "";
        if (CollectionUtils.isEmpty(form.getRepairMaintIds()) && form.getOthrFee().compareTo(new BigDecimal(0)) == 0) {
            feeStatus = "未产生";
        }
        DtsCarTransfer dtsCarTransferDB = new DtsCarTransfer();
        BeanUtils.copyProperties(form, dtsCarTransferDB);
        dtsCarTransferDB.setCreated(new Date());
        dtsCarTransferDB.setStatus((byte) 1);
        dtsCarTransferDB.setShopId(SecurityUtils.getLoginUser().getShopId());
        dtsCarTransferDB.setFeeStatus(feeStatus);
        return dtsCarTransferDB;
    }

    /**
     * 修改租车表
     *
     * @param form
     */
    private void updateDtsCarRental(DtsCarTransferForm form, HttpServletRequest request) {
        //DtsCarTransfer carTransfer = getById(id);
        Long repairCodeAft = form.getRepairCodeAft();
        String vehPhotoAft = form.getVehPhotoAft();
        String remarksAft = form.getRemarksAft();
        DtsCarRental dtsCarRental = new DtsCarRental();
        dtsCarRental.setId(form.getCarRentalId());
        dtsCarRental.setRepairCodeId(repairCodeAft);
        dtsCarRental.setVehiclePhoto(vehPhotoAft);
        dtsCarRental.setVehicleRemark(remarksAft);
        //更改合同
        DtsCarRental carRental = dtsCarRentalService.getById(form.getCarRentalId());
        ContractData contractData = dtsCarRentalService.getContractData(carRental.getId(),
                repairCodeAft, null,
                carRental.getGuaranteeCompanyId(),
                carRental.getContractNo(),
                carRental.getUserSign(),
                form.getCommunityId());
        String content = dtsCarRentalService.getContent(contractData, request);
        dtsCarRental.setContent(content);
        dtsCarRental.setTransferStatus((byte) 1);
        dtsCarRentalService.updateById(dtsCarRental);

    }

    /**
     * 检查是否产生维修费
     *
     * @param form
     */
    private void checked(DtsCarTransferForm form) {
        if (CollectionUtils.isEmpty(form.getRepairMaintIds()) && form.getOthrFee().compareTo(new BigDecimal(0)) == 0) {
            return;
        }
        Long carRentalId = form.getCarRentalId();
        DtsCarTransfer dtsCarTransfer = getOne(new LambdaQueryWrapper<DtsCarTransfer>()
                .eq(DtsCarTransfer::getCarRentalId, carRentalId));
        if (dtsCarTransfer != null && dtsCarTransfer.getIsPay().intValue() != 1) {
            throw new ApiException("请先支付维修费用！");
        }
    }

    /**
     * 修改车辆信息
     *
     * @param form
     */
    public void updateRepairCode(DtsCarTransferForm form) {
        Long repairCodeAft = form.getRepairCodeAft();
        RepairCode repairCode = new RepairCode();
        repairCode.setId(repairCodeAft);
        repairCode.setVehicleStatus((byte) 4);
        repairCodeService.updateById(repairCode);
    }


    /**
     * 修改车辆信息
     *
     * @param form
     */
    /*public void updateRepairCode(DtsCarTransferForm form) {
        Long repairCodeBefId = form.getRepairCodeBef();
        RepairCode repairCodeBef = new RepairCode();
        byte vehicleStatus = 1;
        if (!CollectionUtils.isEmpty(form.getRepairMaintIds())) {
            //之前的车还入站点
            vehicleStatus = 2;
            List<RepairMaint> repairMaints = repairMaintService
                    .list(new LambdaQueryWrapper<RepairMaint>()
                            .in(RepairMaint::getId, form.getRepairMaintIds()));
            if (!CollectionUtils.isEmpty(repairMaints)) {
                List<String> strings = repairMaints.stream().map(RepairMaint::getName).collect(Collectors.toList());
                String unusualLocation = "损坏部位: " + strings.toString();
                repairCodeBef.setUnusualLocation(unusualLocation);
            }
        }
        repairCodeBef.setId(repairCodeBefId);
        repairCodeBef.setVehicleStatus(vehicleStatus);
        repairCodeService.updateByUser(repairCodeBef);
        Long repairCodeAftId = form.getRepairCodeAft();
        RepairCode repairCodeAft = new RepairCode();
        repairCodeAft.setId(repairCodeAftId);
        repairCodeAft.setVehicleStatus((byte) 4);
        repairCodeAft.setRentUser(form.getUserId());
        repairCodeService.updateByUser(repairCodeAft);
    }*/


    /***
     * 锁定新车
     * @param form
     */
    private void lockTheVehicle(DtsCarTransferForm form) {
        if (form.getRepairCodeAft() != null) {
            RepairCode repairCode = new RepairCode();
            repairCode.setId(form.getRepairCodeAft());
            repairCode.setVehicleStatus((byte) 4);
            repairCode.setVehicleBelongs(form.getCommunityId());
            repairCode.setRentUser(form.getUserId());
            repairCodeService.updateById(repairCode);
        }

    }


    /**
     * 换车审核
     *
     * @param id
     * @param status
     * @param transferOpinion
     * @return
     */
    @Override
    public boolean changeReview(Long id, Byte status, String transferOpinion, Long communityId, HttpServletRequest request) {
        DtsCarTransfer transfer = getById(id);
        if (transfer.getStatus() != 1) {
            throw new ApiException("已经审核无需重复审核");
        }
        Byte status1 = 0;
        Byte isPay = 0;
        if (status.intValue() == 1) {
            status1 = 2;
            isPay = 2;
        }
        DtsCarTransfer dtsCarTransfer = new DtsCarTransfer();
        dtsCarTransfer.setId(id);
        dtsCarTransfer.setStatus(status1);
        dtsCarTransfer.setTransferOpinion(transferOpinion);
        dtsCarTransfer.setTransferTime(new Date());
        dtsCarTransfer.setIsPay(isPay);
        updateById(dtsCarTransfer);
        //修改租车表
        if (status.intValue() == 1) {
            //status 1:审核通过 0:审核驳回
            DtsCarTransfer carTransfer = getById(id);
            Long repairCodeAft = carTransfer.getRepairCodeAft();
            String vehPhotoAft = carTransfer.getVehPhotoAft();
            String remarksAft = carTransfer.getRemarksAft();
            DtsCarRental dtsCarRental = new DtsCarRental();
            dtsCarRental.setId(carTransfer.getCarRentalId());
            dtsCarRental.setRepairCodeId(repairCodeAft);
            dtsCarRental.setVehiclePhoto(vehPhotoAft);
            dtsCarRental.setVehicleRemark(remarksAft);
            //更新车辆状态
            updVehSts(id);
            //更改合同
            DtsCarRental carRental = dtsCarRentalService.getById(carTransfer.getCarRentalId());
            ContractData contractData = dtsCarRentalService.getContractData(carRental.getId(), repairCodeAft, null, carRental.getGuaranteeCompanyId(), carRental.getContractNo(), carRental.getUserSign(), communityId);
            String content = dtsCarRentalService.getContent(contractData, request);
            dtsCarRental.setContent(content);
            return dtsCarRentalService.updateById(dtsCarRental);
        } else {
            //释放新车
            releaseNewCar(id);
            //退款
            carTransferRefund(id, transfer.getShopId(), transferOpinion);
            return true;
        }
    }


    /**
     * 退车退款
     *
     * @param id
     */
    private void carTransferRefund(Long id, Long shopId, String transferOpinion) {
        DtsCarTransfer transfer = getById(id);
        if (transfer == null) {
            return;
        }
        Double fee = transfer.getMaintFee().add(transfer.getOthrFee()).doubleValue();
        if (fee != null && fee > 0) {
            if (!StringUtils.isEmpty(transfer.getBizPayNo())) {
                //退款
                String refundNo = IdWorker.getId() + "";
                String notifyUrl = "/lease/dts/carTransfer/refund/notify";
                DtsCarTransferRefund refund = carTransferRefundService.getOne(new LambdaQueryWrapper<DtsCarTransferRefund>()
                        .eq(DtsCarTransferRefund::getCarTransferId, id));
                if (refund != null && refund.getIsRefund() == 1) {
                    payService.carRetreat(shopId, refund.getAppId(), refundNo, refund.getTransactionId(), fee, fee, notifyUrl, transferOpinion);
//                    DtsCarTransferRefund transferRefund = new DtsCarTransferRefund();
//                    transferRefund.setCarTransferId(id);
//                    transferRefund.setFee(fee);
//                    transferRefund.setRefundNo(refundNo);
//                    transferRefund.setTransactionId(transfer.getBizPayNo());
//                    carTransferRefundService.save(transferRefund);
                }
            }
            this.dtsCarTransferMapper.updateIsPay(id);
        }
    }


    /***
     * 释放新车
     * @param id
     */
    private void releaseNewCar(Long id) {
        DtsCarTransfer carTransfer = getById(id);
        if (carTransfer.getRepairCodeAft() != null) {
            RepairCode repairCode = new RepairCode();
            repairCode.setId(carTransfer.getRepairCodeAft());
            repairCode.setVehicleStatus((byte) 1);
            repairCode.setVehicleBelongs(carTransfer.getCommunityId());
            repairCodeService.updateByPrimaryKeySelective(repairCode);
        }
    }


    /***
     * 查询当前骑手换车订单
     * @return
     */
    @Override
    public DtsCarTransferVo getCarTransferByUser() {
        Long userId = SecurityUtils.getUserId();
        DtsCarTransferVo dtsCarTransferVo = dtsCarTransferMapper.getCarTransferByUser(userId);
        if (dtsCarTransferVo != null) {
            List<RepairMaint> repairMaints = getRepairMaintsById(dtsCarTransferVo.getId());
            dtsCarTransferVo.setRepairMaints(repairMaints);
            BigDecimal price = new BigDecimal("0");
            if (!CollectionUtils.isEmpty(repairMaints)) {
                for (RepairMaint maint : repairMaints) {
                    price = price.add(maint.getPrice());
                }
            }
            dtsCarTransferVo.setMaintSum(price);
        }
        return dtsCarTransferVo;
    }

    @Override
    public boolean exchangeFee(Long id, Byte userConfirm, String userOpinion) {
        DtsCarTransfer dtsCarTransfer = new DtsCarTransfer();
        dtsCarTransfer.setId(id);
        dtsCarTransfer.setUserConfirm(userConfirm);
        dtsCarTransfer.setUserOpinion(userOpinion);
        return updateById(dtsCarTransfer);
    }

    /***
     * 查询维修欠款
     * @return
     */
    @Override
    public String maintArrs(Long shopId) {
        return dtsCarTransferMapper.maintArrs(shopId);
    }

    @Override
    public Integer checkPay(Long carRentalId) {
        return dtsCarTransferMapper.checkPay(carRentalId);
    }


    /***
     * 更新车辆状态
     * @param id
     */
    private void updVehSts(Long id) {
        DtsCarTransfer dtsCarTransfer = getById(id);
        List<DtsCarTransferMaint> transferMaints = dtsCarTransferMaintService.list();
        //更新旧车为故障
        Long repairCodeBefId = dtsCarTransfer.getRepairCodeBef();
        RepairCode repairCodeBef = new RepairCode();
        repairCodeBef.setId(repairCodeBefId);
        StringBuffer sb = new StringBuffer("");
        Byte setVehicleStatus = (byte) 1;
        if (!CollectionUtils.isEmpty(transferMaints)) {
            setVehicleStatus = (byte) 2;
            List<RepairMaint> repairMaints = getRepairMaintsById(id);
            if (!CollectionUtils.isEmpty(repairMaints)) {
                for (int i = 0; i < repairMaints.size(); i++) {
                    RepairMaint repairMaint = repairMaints.get(i);
                    if (i != repairMaints.size() - 1) {
                        sb.append(i + 1 + "." + repairMaint.getName()).append("损坏, ");
                    } else {
                        sb.append(i + 1 + "." + repairMaint.getName()).append("损坏;");
                    }
                }
            }
        }
        repairCodeBef.setVehicleStatus(setVehicleStatus);
        repairCodeBef.setUnusualLocation(sb.toString());
        repairCodeBef.setVehicleBelongs(dtsCarTransfer.getCommunityId());
        repairCodeService.updateByPrimaryKeySelective(repairCodeBef);
        //跟新新车
        Long repairCodeAftId = dtsCarTransfer.getRepairCodeAft();
        RepairCode aftRepairCodeAft = repairCodeService.getById(repairCodeAftId);
        aftRepairCodeAft.setRentUser(dtsCarTransfer.getUserId());
        aftRepairCodeAft.setVehicleStatus((byte) 4);
        aftRepairCodeAft.setVehicleBelongs(dtsCarTransfer.getCommunityId());
        repairCodeService.updateById(aftRepairCodeAft);
    }

    /**
     * 更新维修费用
     *
     * @param id
     * @param form
     */
    private void updMaint(Long id, DtsCarTransferForm form) {
        LambdaQueryWrapper<DtsCarTransferMaint> queryWrapper = new LambdaQueryWrapper<DtsCarTransferMaint>()
                .eq(DtsCarTransferMaint::getCarTransferId, id);
        int count = dtsCarTransferMaintService.count(queryWrapper);
        if (count > 0) {
            dtsCarTransferMaintService.remove(queryWrapper);
        }
        if (CollectionUtils.isEmpty(form.getRepairMaintIds())) {
            return;
        }
        List<DtsCarTransferMaint> list = new ArrayList<>(form.getRepairMaintIds().size());
        for (Long repairMaintId : form.getRepairMaintIds()) {
            list.add(new DtsCarTransferMaint(IdWorker.getId(), id, repairMaintId));
        }
        dtsCarTransferMaintService.saveBatch(list);
    }


}
